package com.xjh.t.controller;


import ch.qos.logback.core.joran.spi.ElementSelector;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjh.t.common.*;
import com.xjh.t.domain.*;
import com.xjh.t.service.*;
import com.xjh.t.vo.GroupInfoVo;
import com.xjh.t.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.geom.Area;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-03-12
 */
@RestController
@RequestMapping("/groupInfo")
public class GroupInfoController {

    @Autowired
    private IGroupInfoService groupInfoService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IAreaInfoService areaInfoService;
    @Autowired
    private IOperateLogService operateLogService;

    @Autowired
    private IRequestInfoService requestInfoService;

    @Autowired
    private  IUserService userService;

    private Map<String,Integer> lastDayGroupNum = new HashMap<>();

    @RequestMapping("loadAllCompany")
    public DataGridView loadAllCompany(GroupInfoVo vo)
    {

        IPage<GroupInfo> page = new Page<>(vo.getPage(),vo.getLimit());
        QueryWrapper<GroupInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(vo.getGpName()),"gp_name",vo.getGpName());
       // queryWrapper.like(StringUtils.isNotBlank(vo.getGpAddr()),"gp_addr",vo.getGpAddr());

        queryWrapper.ge(vo.getStartTime() != null,"gp_reg_date",vo.getStartTime());
        queryWrapper.le(vo.getEndTime() != null,"gp_reg_date",vo.getEndTime());

        if(StringUtils.isNotBlank(vo.getAuditUser()))
        {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.like("name",vo.getAuditUser());
            List<User> userList = this.userService.list(userQueryWrapper);
            QueryWrapper<RequestInfo> requestInfoQueryWrapper = new QueryWrapper<>();
            List<Integer> userids = new ArrayList<>();
            for(User user:userList)
                userids.add(user.getId());
            requestInfoQueryWrapper.in(userids.size() > 0,"ur_opt_id",userids);
            List<RequestInfo> requestInfos = this.requestInfoService.list(requestInfoQueryWrapper);
            List<Integer> urids = new ArrayList<>();
            for(RequestInfo requestInfo:requestInfos)
                urids.add(requestInfo.getUrId());
            queryWrapper.in(urids.size() > 0,"ur_id",urids);
        }
        //queryWrapper.like(StringUtils.isNotBlank(vo.getAuditUser()),"gp_reg_date",vo.getEndTime());

        if(StringUtils.isNotBlank(vo.getGpAddr()))
        {
            QueryWrapper<AreaInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.like("aa_areaname",vo.getGpAddr());
            List<AreaInfo> addrIds = this.areaInfoService.list(queryWrapper1);
            List<Integer> areaIds = new ArrayList<>();

            if(addrIds.size() > 0)
            {
                AreaInfo areaInfo1 = addrIds.get(0);
                String serachid = areaInfo1.getAaId().toString().substring(0,areaInfo1.getAaLevel()*2);
                List<AreaInfo> areaInfos = this.areaInfoService.queryAreaInfoByParentId("%" + serachid + "%");
                for(AreaInfo areaInfo:areaInfos)
                    areaIds.add(areaInfo.getAaId());
                queryWrapper.in("gp_zone",areaIds);

            }

        }
        if(StringUtils.isNotBlank(vo.getCreateUserAccount()))
        {
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.like(vo.getCreateUserAccount() != null,"ur_phonenumber",vo.getCreateUserAccount());
            List<UserInfo> userInfoList = this.userInfoService.list(userInfoQueryWrapper);
            List<Integer> userids = new ArrayList<>();
            for(UserInfo userInfo:userInfoList)
            {
                userids.add(userInfo.getUrId());
            }
            queryWrapper.in(userids.size() > 0,"ur_id",userids);
        }

        queryWrapper.orderByDesc("gp_reg_date");
        this.groupInfoService.page(page,queryWrapper);

        List<UserInfo> userInfos = this.userInfoService.list();
        Map<Integer,String> userAccount = userInfos.stream().collect(Collectors.toMap(UserInfo::getUrId, UserInfo::getUrPhonenumber));
        List<GroupInfo> list = page.getRecords();
        List<GroupInfoVo> result = new ArrayList<>();
        for(GroupInfo g1:list)
        {
            GroupInfoVo groupInfoVo = new GroupInfoVo();
            BeanUtils.copyProperties(g1,groupInfoVo);
            if(userAccount.get((groupInfoVo.getUrId().intValue())) != null)
                groupInfoVo.setCreateUserAccount(userAccount.get(groupInfoVo.getUrId().intValue()));
            else
                groupInfoVo.setCreateUserAccount("");

            String addr = "";
            AreaInfo areaInfo = this.areaInfoService.getById(groupInfoVo.getGpZone());
            while (areaInfo != null && areaInfo.getAaLevel() != Constast.POLICY_TOP_LEVEL)
            {
                addr = areaInfo.getAaAreaname() + " " + addr;
                areaInfo = this.areaInfoService.getById(areaInfo.getAaParentid());
            }
            if(areaInfo == null)
            {
                System.out.println(groupInfoVo.getGpId() + "," + groupInfoVo.getGpName());
            }
            else
                addr = areaInfo.getAaAreaname() + " " + addr;

            groupInfoVo.setGpPolicyAddr(addr);

            QueryWrapper<RequestInfo> requestInfoQueryWrapper = new QueryWrapper<>();
            requestInfoQueryWrapper.eq("ur_id",groupInfoVo.getUrId());
            List<RequestInfo> requestInfos = this.requestInfoService.list(requestInfoQueryWrapper);
            if(requestInfos.size() > 0)
            {
                User user = this.userService.getById(requestInfos.get(0).getUrOptId());
                if(user != null)
                {
                    groupInfoVo.setAuditUser(user.getName());
                }
            }

            result.add(groupInfoVo);
        }

        return new DataGridView(page.getTotal(),result);
    }

    @RequestMapping("charge")
    public ResultObj charge(@RequestParam("phoneNumber") String phonenumber,@RequestParam("chargeNum") float chargeNum)
    {
       // if(gvo.getChargeNum() != null)

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ur_phonenumber",phonenumber);
        List<UserInfo> userInfoList = this.userInfoService.list(queryWrapper);
        if(userInfoList.size() == 1) {

            QueryWrapper<GroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
            groupInfoQueryWrapper.eq("ur_id",userInfoList.get(0).getUrId());

            List<GroupInfo> groupInfoList = this.groupInfoService.list(groupInfoQueryWrapper);

            User user =  (User) WebUtils.getSession().getAttribute("user");

            if(user == null)
                return  ResultObj.OFFLINE_ERROR;

            if(groupInfoList.size() == 1 && user != null) {
                if (groupInfoList.get(0) != null) {
                    groupInfoList.get(0).setGpBalance(groupInfoList.get(0).getGpBalance() + chargeNum);
                    this.groupInfoService.updateById(groupInfoList.get(0));

                    OperateLog operateLog = new OperateLog();
                    operateLog.setOpId(user.getId());
                    operateLog.setOpUsername(user.getName());
                    operateLog.setOpType(Constast.OPERATE_TYPE.CHARGE.ordinal());
                    StringBuilder builder = new StringBuilder();
                    builder.append("代客充值,");
                    builder.append("充值账号：" + phonenumber + ",");
                    builder.append("充值金额：" + chargeNum);
                    operateLog.setOpMsg(builder.toString());
                    operateLog.setOpData( Float.toString(chargeNum));
                    operateLog.setOpTime(new Date());
                    this.operateLogService.save(operateLog);
                    return ResultObj.CHARGE_SUCESS;
                } else
                    return ResultObj.CHARGE_ERROR;
            }
            else
                return ResultObj.CHARGE_ERROR_NO_GROUP;

        }
        else
        {
            return ResultObj.CHARGE_ERROR_NO_USER;
        }

    }

    @RequestMapping("getDayGroupChart")
    public ChartData getDayGroupChart() throws Exception {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        Integer i=10;
        Date starttime;
        Date endtime;

       // List<Float> amountList = new ArrayList();
        List<String> timelist = new ArrayList();
        List<Integer> groupNumList = new ArrayList();

        for (; i >= 0; i--) {


            QueryWrapper<GroupInfo> queryWrapper = new QueryWrapper<>();

            Date date = sdf.parse("2020-03-08 00:00:00");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            calendar.add(Calendar.DAY_OF_MONTH, -i);
            String datestr = simpleDateFormat.format(calendar.getTime());

            if(lastDayGroupNum.get(datestr) != null)
            {
                groupNumList.add(lastDayGroupNum.get(datestr));
                timelist.add(datestr);
            }
            else {
                starttime = sdf.parse(datestr + " 00:00:00");
                endtime = sdf.parse(datestr + " 23:59:59");

                timelist.add(datestr);

                queryWrapper.ge(starttime != null, "gp_reg_date", starttime);
                queryWrapper.le(endtime != null, "gp_reg_date", endtime);

                System.out.println("查询日期：" + datestr);
                List<GroupInfo> groupInfos = this.groupInfoService.list(queryWrapper);

                groupNumList.add(groupInfos.size());
                if(i !=0) {
                    lastDayGroupNum.put(datestr, groupInfos.size());
                }
            }

        }



        return new ChartData(groupNumList.size(),timelist,groupNumList);
    }

    @RequestMapping("getAllOuputCenter")
    public DataGridView getAllOuputCenter() throws Exception {

        List<TreeNode> nodes = new ArrayList<>();
        Integer i = 0;

        String[] outputCenter = {"0","义乌物与喷印","浙江禾物喷印","无锡点优","淄博红印彩绘","潍坊皓程喷印","青州源艺喷印","株洲新颖喷印","九江优绘喷印","修水怡佳喷印","杭州禾物喷印","苏州物与喷印"};

        for(;i < outputCenter.length;i++)
        {
            TreeNode node = new TreeNode(i,0,outputCenter[i],false);
            nodes.add(node);
        }

        return new DataGridView(nodes);
    }


}

